<?php

namespace app\common\lib;

use Symfony\Component\Console\Command\LazyCommand;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Throwable;
use Webman\Console\Command;
use Webman\Console\Util;

class CommandUtil extends Command
{
    public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN')
    {
        parent::__construct($name, $version);
        if (is_dir($command_path = Util::guessPath(app_path(), '/command', true))) {
            $this->installCommands($command_path);
        }
    }

    /**
     * 执行命令
     * @param string $commandStr
     * @return int
     * @throws Throwable
     */
    public function handle(string $commandStr): int
    {
        $command = $this->find($commandStr);
        if ($command instanceof LazyCommand) {
            $command = $command->getCommand();
        }
        $input  = new ArgvInput();
        $output = new ConsoleOutput();
        return $this->doRunCommand($command, $input, $output);
    }

    /**
     * 调用命令的静态方法
     * @param string $commandStr
     * @return void
     * @throws Throwable
     */
    public static function call(string $commandStr)
    {
        $command = new self();
        $command->handle($commandStr);
    }
}
